﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Omu.AwesomeDemo.Core;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Service;
using Omu.AwesomeDemo.Infra.Builder;
using Omu.AwesomeDemo.Infra.Dto;

namespace Omu.AwesomeDemo.WebUI.Controllers
{
    public class ListBindingController : BaseController
    {
        private readonly ICrudService<Foobar> s;
        private readonly IBuilder<Foobar, FoobarInput> v;

        public ListBindingController(ICrudService<Foobar> s, IBuilder<Foobar, FoobarInput> v)
        {
            this.s = s;
            this.v = v;
        }

        public ActionResult Index()
        {
            return View(s.GetPageable(1, 3).Page.Select(o => v.BuildInput(o)).ToList());
        }

        [HttpPost]
        public ActionResult Index(IList<FoobarInput> inputs)
        {
            try
            {
                if (!ModelState.IsValid) return View(inputs);
                foreach(var o in inputs)
                    s.Save(v.BuildEntity(o));
            }
            catch (AwesomeDemoException ex)
            {
                ModelState.AddModelError("", ex.Message);
                return View(inputs);
            }
            return RedirectToAction("index");
        }
    }
}